<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="用户名/手机号" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="行业" prop="industry">
          <el-input v-model="queryParams.industry" placeholder="行业" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="queryParams.city" placeholder="城市" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="类型" prop="project_type">
          <el-select v-model="queryParams.project_type" placeholder="全部" clearable class="!w-[200px]">
            <el-option label="全部" :value="0" />
            <el-option label="项目库" :value="1" />
            <el-option label="合伙人" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="audit">
          <el-select v-model="queryParams.audit" placeholder="全部" clearable class="!w-[200px]">
            <el-option label="全部" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="通过" :value="2" />
            <el-option label="驳回" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="考察状态" prop="is_investigate">
          <el-select v-model="queryParams.is_investigate" placeholder="全部" clearable class="!w-[200px]">
            <el-option label="全部" :value="0" />
            <el-option label="待考察" :value="1" />
            <el-option label="已通过" :value="2" />
            <el-option label="已驳回" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否用户发布" prop="is_user">
          <el-select v-model="queryParams.is_user" placeholder="全部" clearable class="!w-[200px]">
            <el-option label="全部" :value="0" />
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex-x-between">
          <div>
            <el-button v-hasPerm="['project/add']" type="success" @click="handleOpenDialog()">
              <i-ep-plus />
              发布
            </el-button>
            <el-button v-hasPerm="['project/del']" type="danger" :disabled="removeIds.length === 0"
              @click="handleDelete()">
              <i-ep-delete />
              删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="编号" align="center" type="index" width="80" />
        <el-table-column label="缩略图" align="center" prop="title" width="150">
          <template #default="{ row }">
            <el-image preview-teleported style="width: 60px; height: 60px" :src="row.image" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" :preview-src-list="[row.image]" :initial-index="1" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="项目名" align="center" prop="name" width="200" />
        <el-table-column label="手机号码" align="center" width="120">
          <template #default="{ row }">
            <span @click="handleInfo(row.id)" class="text-[#4080FF] cursor-pointer">{{ row.tel }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="city" width="100">
          <template #default="scope">
            <span v-if="scope.row.project_type == 0">项目库</span>
            <span v-else-if="scope.row.project_type == 1">合伙人</span>
          </template>
        </el-table-column>
        <el-table-column label="行业" align="center" prop="in_name" width="140" />
        <el-table-column label="城市" align="center" prop="area_name" width="120" />
        <el-table-column label="审核状态" align="center" width="200">
          <template #default="scope">
            <span v-if="scope.row.send_audit == 1">通过</span>
            <span v-else-if="scope.row.send_audit == 2">驳回</span>
            <span v-else-if="scope.row.send_audit == 0">待审核</span>
          </template>
        </el-table-column>
        <el-table-column label="审核时间" align="center" width="180">
          <template #default="scope">
            <template v-if="scope.row.send_audit_time > 0">
              {{ formatTimestamp(scope.row.send_audit_time * 1000) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="考察状态" align="center" width="100">
          <template #default="scope">
            <span v-if="scope.row.is_investigate == 1">通过</span>
            <span v-else-if="scope.row.is_investigate == 2">驳回</span>
            <span v-else-if="scope.row.is_investigate == 0">待考察</span>
          </template>
        </el-table-column>
        <el-table-column label="考察时间" align="center" width="180">
          <template #default="scope">
            <template v-if="scope.row.investigate_time > 0">
              {{ formatTimestamp(scope.row.investigate_time * 1000) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="是否上线" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status == 0 ? 'success' : 'info'">
              {{ scope.row.status == 0 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="发布时间" align="center" width="180">
          <template #default="scope">
            <template v-if="scope.row.created_at > 0">
              {{ formatTimestamp(scope.row.created_at * 1000) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="scope">
            <!-- <el-button v-hasPerm="['project/info']" type="primary" link size="small" @click="handleInfo(scope.row.id)">
              <i-ep-Tickets />
              详情
            </el-button> -->
            <el-button v-hasPerm="['project/investigate']" v-if="scope.row.is_investigate == 0" type="primary" link
              size="small" @click="handleInvestigate(scope.row.id)">
              <i-ep-connection />
              考察
            </el-button>
            <el-button v-hasPerm="['project/edit']" type="primary" link size="small"
              @click="handleOpenDialog(scope.row.id)">
              <i-ep-edit />
              编辑
            </el-button>
            <el-button v-hasPerm="['project/del']" type="danger" link size="small" @click="handleDelete(scope.row.id)">
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- 发布修改表单弹窗 -->
    <el-drawer v-model="dialog.visible" size="50%" :title="dialog.title" append-to-body @close="handleCloseDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="类型" prop="project_type">
              <el-radio-group v-model="formData.project_type">
                <el-radio :value="0">项目库</el-radio>
                <el-radio :value="1">合伙人</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目全称" prop="project_name">
              <el-input v-model="formData.project_name" placeholder="请输入项目全称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city_id">
              <el-select v-model="formData.city_id" clearable filterable placeholder="请选择城市">
                <el-option v-for="item in areaList" :label="item.area_name" :value="+item.area_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行业" prop="industry">
              <el-tree-select :props="{ label: 'name' }" node-key="id" v-model="formData.industry" :data="industryList"
                :render-after-expand="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="label">
              <el-select multiple filterable allow-create v-model="formData.label" clearable placeholder="请输入标签">
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="tel">
              <el-input v-model="formData.tel" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="formData.qq" placeholder="请输入QQ号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信" prop="wechat">
              <el-input v-model="formData.wechat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱号" prop="emil">
              <el-input v-model="formData.emil" placeholder="请输入邮箱号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目简介" prop="describe">
              <el-input type="textarea" v-model="formData.describe" placeholder="请输入项目简介" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目内容" prop="content">
              <el-input type="textarea" v-model="formData.content" placeholder="请输入项目内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目主图" prop="proImage">
              <image-upload v-if="dialog.visible" :limit="1" v-model="formData.proImage" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目图片" prop="proImages">
              <image-upload v-if="dialog.visible" :limit="9" v-model="formData.proImages" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="风险描述" prop="risk_description">
              <el-input type="textarea" v-model="formData.risk_description" placeholder="请输入风险描述" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目评估" prop="assessment">
              <el-input type="textarea" v-model="formData.assessment" placeholder="请输入项目评估" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目利益" prop="related_interests">
              <el-input type="textarea" v-model="formData.related_interests" placeholder="请输入项目利益" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目总预算" prop="budget">
              <el-input type="number" v-model.number="formData.budget" placeholder="请输入项目总预算" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="text-[16px] mt-[30px] mb-[10px] flex items-center">
              <div class="mr-[10px]">项目计划</div>
              <el-button type="primary" @click="addPlan" size="small">新增计划</el-button>
            </div>
            <el-row v-for="(item, index) in formData.plan" :key="item.id">
              <el-col :span="24">
                <div class="text-right mb-[20px]" v-if="index !== 0">
                  <el-button type="danger" size="small" @click="removePlan(index)">删除</el-button>
                </div>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计划名" prop="plan.name">
                  <el-input type="text" v-model="item.name" placeholder="请输入计划名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预算" prop="plan.budget">
                  <el-input type="number" v-model.number="item.budget" placeholder="请输入预算" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <div class="date-picker">
                  <el-form-item label="开始时间" prop="start_time">
                    <el-date-picker value-format="x" v-model="item.start_time" type="date" placeholder="请选择开始时间" />
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="date-picker">
                  <el-form-item label="结束时间" prop="end_time" class="!w-[100%]">
                    <el-date-picker value-format="x" v-model="item.end_time" type="date" placeholder="请选择结束时间" />
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="24">
                <el-form-item label="描述" prop="other">
                  <el-input type="textarea" v-model="item.other" placeholder="请输入描述" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <div class="text-[16px] mt-[30px] mb-[10px] flex items-center">
              <div class="mr-[10px]">相关资料</div>
              <el-button type="primary" @click="addProjectPartnerData" size="small">新增资料</el-button>
            </div>
            <el-row v-for="(item, index) in formData.project_partner_data" :key="index">
              <el-col :span="24">
                <div class="text-right mb-[20px]" v-if="index !== 0">
                  <el-button type="danger" size="small" @click="removeProjectPartnerData(index)">删除</el-button>
                </div>
              </el-col>
              <el-col :span="24">
                <div class="date-picker">
                  <el-form-item label="资料名称" prop="name">
                    <el-input type="text" v-model="item.name" placeholder="请输入资料名称" />
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="24">
                <el-form-item label="图片">
                  <image-upload v-if="dialog.visible" :limit="9" v-model="item.images" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer v-model="drawerVisible" title="项目真实性考察">
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="是否真实" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio value="commit">是</el-radio>
            <el-radio value="return">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="other">
          <el-input type="textarea" v-model="form.other" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <image-upload v-if="drawerVisible" :limit="9" v-model="form.images" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleInvestigateSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import router from "@/router";
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import ProjectAPI, { UserForm, PageQuery, UserPageVO, area } from "@/api/partner";
import { formatTimestamp } from '@/utils/index'
import ImageUpload from "@/components/Upload/ImageUpload.vue";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);
const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<UserPageVO[]>();
/** 部门下拉选项 */
const deptOptions = ref<OptionType[]>();
/** 角色下拉选项 */
// const roleOptions = ref<OptionType[]>();
/** 用户查询参数  */
const queryParams = reactive<PageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const drawerVisible = ref(false);

const handleInvestigateSubmit = () => {
  drawerVisible.value = false;
  form.image = form.images.length > 0 ? form.images.join(",") : "";
  ProjectAPI.postInvestigate(form).then(res => {
    drawerVisible.value = false;
    ElMessage.success("操作成功");
    handleResetQuery();
  })
}


// 跳转详情
const handleInfo = (id: number) => {
  router.push({ path: 'partnerInfo', query: { id: id } });
}

// 真实性数据
const form = reactive({
  id: 0,
  type: "commit",
  other: "",
  images: [],
  image: ""
})

// 提交
const handleInvestigate = (id: number) => {
  form.id = id;
  drawerVisible.value = true;
}

/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

const addPlan = () => {
  formData.plan.push({
    name: '',
    budget: 0,
    start_time: '',
    end_time: '',
    other: '',
  })
}

const removePlan = (index: number) => {
  formData.plan.splice(index, 1);
}

const addProjectPartnerData = () => {
  formData.project_partner_data.push({
    name: '',
    images: [],
  })
}

const removeProjectPartnerData = (index: number) => {
  formData.project_partner_data.splice(index, 1);
}


// 用户表单数据
const formData = reactive<UserForm>({
  project_type: 0,
  status: 1,
  is_vip: 0,
  plan: [],
  project_partner_data: [],
});

/** 用户表单校验规则  */
const rules = reactive({
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  ProjectAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改";
    ProjectAPI.getFormData({ id }).then((data) => {
      data.proImages = data.images == "" ? [] : data.images.split(',');
      data.proImage = data.image == "" ? [] : data.image.split(',');
      // 项目计划图片转换为数组
      if (data.project_partner_data) {
        data.project_partner_data.forEach((item: any) => {
          item.images = item.image == "" ? [] : item.image.split(',');
        });
      }

      if (data.plan) {
        data.plan.forEach((item: any) => {
          item.end_time = item.end_time == 0 ? '' : item.end_time * 1000;
          item.start_time = item.start_time == 0 ? '' : item.start_time * 1000;
        });
      }
      let info = { ...data };
      Object.assign(formData, info);
    });
  } else {
    dialog.title = "发布";
  }
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  drawerVisible.value = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.project_partner_data = [];
  formData.plan = [];
  formData.id = undefined;
  formData.status = 1;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      formData.images = formData.proImages.length > 0 ? formData.proImages.join(',') : "";
      formData.image = formData.proImage.length > 0 ? formData.proImage.join(',') : "";
      formData.project_partner_data.forEach((item: any) => {
        item.image = item.images.length > 0 ? item.images.join(',') : "";
      });
      formData.plan.forEach((item: any) => {
        item.end_time = item.end_time / 1000;
        item.start_time = item.start_time / 1000;
      });
      loading.value = true;
      if (userId) {
        ProjectAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ProjectAPI.add(formData)
          .then(() => {
            ElMessage.success("发布成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = id ? [id] : removeIds.value;

  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      ProjectAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}


const areaList = ref<area[]>([]);
const industryList = ref([]);
const hanldeAreaList = () => {
  ProjectAPI.getAreaList().then(res => {
    areaList.value = res;
  })
  ProjectAPI.getIndustryList().then(res => {
    industryList.value = res as any;
  })
};

onMounted(() => {
  handleQuery();
  hanldeAreaList();
});
</script>

<style scoped>
.date-picker :deep(.el-form-item__content),
.date-picker :deep(.el-form-item__content) div {
  width: 100% !important;
}
</style>
